<script setup lang="ts">
import useGetCategory from "@/hooks/useGetCategory";
import { computed, ref, watch } from "vue";

const { list, listMap } = useGetCategory();

const modelValue = defineModel<number | string>();
const index = ref([0, 0]);

let flag = true;

watch(
  [modelValue, listMap],
  ([id, map]) => {
    if (map.size && id && flag) {
      flag = false;

      const pId = map.get(id)["p_id"];
      const parent = map.get(pId);

      const pIndex = list.value.findIndex((e) => (e.id = pId));
      const cIndex = parent.children.findIndex((e) => e.id == id);

      index.value = [pIndex, cIndex];
    }
  },
  {
    immediate: true,
  }
);

const range = computed(() => {
  const [p] = index.value;
  const { value } = list;

  return value?.length > 0 ? [value, value?.[p]["children"] || []] : [];
});

const handleChange = () => {
  const [_, c] = index.value;
  modelValue.value = range.value[1][c]["id"];
};

const handleColumnchange = ({ detail: { column, value } }) => {
  index.value[column] = value;
  if (column == 0) {
    index.value[1] = 0;
  }
};

const showText = computed(() => {
  const { value } = modelValue;
  const current = listMap.get(value);
  return current?.title;
});
</script>

<template>
  <picker
    mode="multiSelector"
    :value="index"
    :range="range"
    range-key="title"
    @change="handleChange"
    @columnchange="handleColumnchange"
  >
    <slot :title="showText" />
  </picker>
</template>
